from flask import Flask
from recbole.quick_start import load_data_and_model
from recbole.utils.case_study import full_sort_topk
import json
from flask_cors import cross_origin

app = Flask(__name__)

config, model, dataset, train_data, valid_data, test_data = load_data_and_model(
        model_file='saved/BPR-Mar-09-2022_17-06-19.pth',
        # model_file='E:\code\Pycharm\RecBole\saved\LR-Mar-08-2022_20-18-23.pth',
    )  # Here you can replace it by your model path.

with open('problemId_tag_type_new_id.json') as f:
    problems = json.load(f)

def getRecProblemId(user_id):
    uid_series = dataset.token2id(dataset.uid_field, [str(user_id)])
    test_data.is_sequential = True
    topk_score, topk_iid_list = full_sort_topk(uid_series, model, test_data, k=10, device=config['device'])
    # print('topk_score:', topk_score)
    iids = topk_iid_list[:1][0].numpy().tolist()
    scores = topk_score[:1][0].numpy().tolist()
    if len(iids) <= 0 :
        return {"topk_iid_list":''}
    # r = [d for d in result if d >= 5000]
    result = list()
    for i in range(len(iids)):
        if iids[i]<5000:
            continue
        result.append({'id':iids[i],'problem':problems[str(iids[i])]})
    return {"topk_iid_list": result}

@app.route('/')
def hello_world():
    return 'Hello World!'

@cross_origin()
@app.route("/user/recbole/<int:user_id>")
def getRecommendationByUserId(user_id):
    result = getRecProblemId(user_id)
    return json.dumps(result)

if __name__ == '__main__':
    app.run()
